package com.pool.store;

import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;

import com.pool.common.Lists;
import com.pool.common.Shoot;

/**
 * @author claveld@gmail.com (David Clavel)
 */
public class ShootStore implements Store<Shoot> {

  protected static final String TABLE = "SHOTS";
  
  private final Database database;

  public ShootStore() {
    this(Database.get());
  }
  
  public ShootStore(Database database) {
    this.database = database;
  }

  public boolean add(Shoot shoot) {
    ContentValues values = new ContentValues();
    values.put("Id", shoot.id);
    values.put("Description", shoot.description);
    values.put("Bonus", shoot.bonus);
    database.insert(TABLE, null, values);
    return true;
  }
  
  public boolean update(Shoot e) {
    // Currently, no need to update.
    throw new UnsupportedOperationException("Not implemented.");
  }
  public boolean delete(Shoot e) {
    // Currently, no need to delete.
    throw new UnsupportedOperationException("Not implemented.");
  }

  public boolean deleteAll() {
    database.delete(TABLE, "", null);
    return true;
  }
  
  public Shoot get(String id) {
    // TODO(claveld): completely not optimized. Query DB instead.
    for (Shoot shoot : getAll()) {
      if (shoot.id.equals(id)) {
        return shoot;
      }
    }
    return null;
  }
  
  public List<Shoot> getAll() {
    String[] columns = {"Id", "Description", "Bonus"};
    Cursor cursor = database.query(TABLE, columns, null, null, null, null, null);
    
    int rowsCount = cursor.getCount();
    List<Shoot> shoots = Lists.newArrayList(rowsCount);
    cursor.moveToFirst();
    for (int i = 0; i < rowsCount; i++) {
      shoots.add(new Shoot(cursor.getString(0),
                            cursor.getString(1),
                            cursor.getInt(2)));
      cursor.moveToNext();
    }
    cursor.close();
    return shoots;
  }
  
  public int getCount() {
    // TODO(claveld): use SELECT COUNT(*) something like that.
    String[] columns = {"Id"};
    Cursor cursor = database.query(TABLE, columns, null, null, null, null, "Id");
    int count = cursor.getCount();
    cursor.close();
    return count;
  }
}
